<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button style="float: right; margin-left: 10px" type="text" @click="goBack">返回</el-button>
        <el-button style="float: right; margin-left: 10px" type="text" @click="handleEdit">修改</el-button>
        <el-button style="float: right" type="primary" @click="continueWriting">继续创作</el-button>
      </div>
      <div class="novel-detail">
        <div class="novel-info">
          <el-image 
            :src="novelInfo.coverUrl" 
            :preview-src-list="[novelInfo.coverUrl]"
            class="novel-cover"
            fit="cover">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
          <div class="novel-content">
            <h2>{{ novelInfo.title }}</h2>
            <p class="author">作者：{{ novelInfo.authorName }}</p>
            <p class="category">分类：{{ novelInfo.categoryName }}</p>
            <p class="status">状态：{{ novelInfo.status === '1' ? '连载中' : '已完结' }}</p>
            <p class="word-count">字数：{{ formatNumber(novelInfo.wordCount) }}</p>
            <p class="update-time">更新时间：{{ formatDate(novelInfo.updateTime) }}</p>
          </div>
        </div>
        <div class="novel-stats">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="stat-item">
                <span class="stat-label">阅读量</span>
                <span class="stat-value">{{ formatNumber(novelInfo.pass) }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <span class="stat-label">点击量</span>
                <span class="stat-value">{{ formatNumber(novelInfo.clicks) }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <span class="stat-label">收藏数</span>
                <span class="stat-value">{{ formatNumber(novelInfo.collection) }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="novel-description">
          <h3>作品简介</h3>
          <p>{{ novelInfo.description }}</p>
        </div>
        <div class="chapter-list">
          <h3>章节列表</h3>
          <el-table :data="chapterList" style="width: 100%" @row-click="handleChapterClick">
            <el-table-column prop="orderNum" label="章节序号" width="120" />
            <el-table-column prop="chapterTitle" label="章节标题" />
            <el-table-column prop="subscribe" label="订阅状态" width="120">
              <template slot-scope="scope">
                <el-tag :type="scope.row.subscribe === 1 ? 'success' : 'info'">
                  {{ scope.row.subscribe === 1 ? '订阅' : '免费' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>

    <!-- 修改对话框 -->
    <el-dialog title="修改小说信息" :visible.sync="editDialogVisible" width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="100px">
        <el-form-item label="小说名称" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入小说名称" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryName">
          <el-input v-model="editForm.categoryName" placeholder="请输入分类" />
        </el-form-item>
        <el-form-item label="封面图片" prop="coverUrl">
          <el-upload
            class="cover-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleCoverChange"
            :before-upload="beforeCoverUpload">
            <img v-if="editForm.coverUrl" :src="editForm.coverUrl" class="cover">
            <i v-else class="el-icon-plus cover-uploader-icon"></i>
          </el-upload>
          <div class="upload-tip">建议尺寸：600x800像素，支持jpg、png格式</div>
        </el-form-item>
        <el-form-item label="作品简介" prop="description">
          <el-input type="textarea" v-model="editForm.description" :rows="4" placeholder="请输入作品简介" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getNovelDetail, getChapterDetail, updateNovel, uploadCover } from "@/api/writer/writer";

export default {
  name: "NovelDetail",
  data() {
    return {
      novelInfo: {
        title: '',
        authorName: '',
        categoryName: '',
        description: '',
        coverUrl: '',
        wordCount: '',
        collection: '',
        pass: 0,
        status: '',
        updateTime: '',
        clicks: 0
      },
      chapterList: [],
      editDialogVisible: false,
      editForm: {
        oldTitle: '',
        title: '',
        categoryName: '',
        coverUrl: '',
        description: ''
      },
      editRules: {
        title: [
          { required: true, message: '请输入小说名称', trigger: 'blur' }
        ],
        categoryName: [
          { required: true, message: '请输入分类', trigger: 'blur' }
        ],
        coverUrl: [
          { required: true, message: '请上传封面图片', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入作品简介', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getNovelDetail();
    this.getChapterList();
  },
  methods: {
    getNovelDetail() {
      const title = this.$route.query.title;
      getNovelDetail(title).then(response => {
        this.novelInfo = response.data.data;
      });
    },
    getChapterList() {
      const title = this.$route.query.title;
      getChapterDetail(title).then(response => {
        this.chapterList = response.data.rows;
      });
    },
    handleEdit() {
      this.editForm = {
        oldTitle: this.novelInfo.title,
        title: this.novelInfo.title,
        categoryName: this.novelInfo.categoryName,
        coverUrl: this.novelInfo.coverUrl,
        description: this.novelInfo.description
      };
      this.editDialogVisible = true;
    },
    beforeCoverUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('上传文件只能是图片格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },
    handleCoverChange(file) {
      const formData = new FormData()
      formData.append('file', file.raw)
      uploadCover(formData).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess('上传成功')
          this.editForm.coverUrl = response.data.url
          // 立即更新预览图
          this.$nextTick(() => {
            this.$refs.editForm.validateField('coverUrl')
          })
        } else {
          this.$modal.msgError(response.msg || '上传失败')
        }
      }).catch(error => {
        this.$modal.msgError('上传失败：' + error.message)
      })
    },
    submitEdit() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          if (!this.editForm.coverUrl) {
            this.$message.warning('请上传封面图片');
            return;
          }
          const updateData = {
            oldTitle: this.editForm.oldTitle,
            title: this.editForm.title,
            categoryName: this.editForm.categoryName,
            coverUrl: this.editForm.coverUrl,
            description: this.editForm.description
          };
          updateNovel(updateData).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess("修改成功");
              this.editDialogVisible = false;
              this.getNovelDetail();
              this.getChapterList();
            } else {
              this.$modal.msgError(response.msg || '修改失败');
            }
          }).catch(error => {
            this.$modal.msgError('修改失败：' + error.message);
          });
        }
      });
    },
    goBack() {
      this.$router.push('/writer/writer');
    },
    continueWriting() {
      this.$router.push({
        path: '/writer/createChapter',
        query: {
          title: this.novelInfo.title
        }
      });
    },
    formatNumber(num) {
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
    },
    handleChapterClick(row) {
      this.$router.push({
        path: '/novel/chapterRead',
        query: {
          title: this.novelInfo.title,
          orderNum: row.orderNum
        }
      });
    }
  }
};
</script>

<style scoped>
.novel-detail {
  padding: 20px;
}

.novel-info {
  display: flex;
  margin-bottom: 30px;
}

.novel-cover {
  width: 200px;
  height: 300px;
  border-radius: 4px;
  margin-right: 30px;
}

.novel-content {
  flex: 1;
}

.novel-content h2 {
  margin: 0 0 20px 0;
  font-size: 24px;
}

.novel-content p {
  margin: 10px 0;
  color: #666;
}

.novel-stats {
  margin: 30px 0;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.stat-item {
  text-align: center;
  padding: 10px;
}

.stat-label {
  display: block;
  color: #909399;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  color: #303133;
}

.novel-description {
  margin-top: 30px;
}

.novel-description h3 {
  margin-bottom: 15px;
  color: #303133;
}

.novel-description p {
  line-height: 1.8;
  color: #606266;
}

.chapter-list {
  margin-top: 30px;
}

.chapter-list h3 {
  margin-bottom: 15px;
  color: #303133;
}

.cover-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 200px;
  height: 300px;
}

.cover-uploader:hover {
  border-color: #409EFF;
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 300px;
  line-height: 300px;
  text-align: center;
}

.cover {
  width: 200px;
  height: 300px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style> 